#include <iostream>
#include <string>
#include <regex>
#include <cstdlib>

std::string resolveEnvironmentVariables(const std::string& path) {
    if (path.empty()) {
        return path;
    }
    
    std::string result = path;
    
    // 查找并替换环境变量，格式为 $VAR_NAME 或 ${VAR_NAME}
    std::regex envVarRegex(R"(\$(\w+|\{[^}]+\}))");
    std::smatch matches;
    
    try {
        while (std::regex_search(result, matches, envVarRegex)) {
            std::string varExpression = matches[0].str();  // 完整的变量表达式，如 $PROJ_ROOT 或 ${PROJ_ROOT}
            std::string varName = matches[1].str();        // 变量名，如 PROJ_ROOT
            
            // 处理 ${VAR_NAME} 格式，移除花括号
            if (!varName.empty() && varName.front() == '{' && varName.back() == '}') {
                varName = varName.substr(1, varName.length() - 2);
            }
            
            // 获取环境变量值
            const char* envValue = std::getenv(varName.c_str());
            std::string replacement = (envValue != nullptr) ? envValue : varExpression;  // 如果环境变量不存在，保持原样
            
            // 替换第一个匹配项
            result = matches.prefix().str() + replacement + matches.suffix().str();
        }
    } catch (const std::exception& e) {
        // 如果正则表达式处理出错，返回原始路径
        std::cerr << "Warning: Environment variable resolution failed for path: " << path << std::endl;
        return path;
    }
    
    return result;
}

int main() {
    // 设置环境变量进行测试
    setenv("PROJ_ROOT", "/home/apachee/trunk/Crystal/CrystalFlowAnalyzer/a9soc", 1);
    
    // 测试环境变量解析
    std::string testPaths[] = {
        "$PROJ_ROOT/design/usb2/src/usb2_DWC_usb3_params.v",
        "${PROJ_ROOT}/design/usb2/src/usb2_DWC_usb3_params.v",
        "/absolute/path/to/file.v"
    };
    
    for (const auto& testPath : testPaths) {
        std::string resolvedPath = resolveEnvironmentVariables(testPath);
        std::cout << "Original: " << testPath << std::endl;
        std::cout << "Resolved: " << resolvedPath << std::endl;
        std::cout << "---" << std::endl;
    }
    
    return 0;
}